package com.example.CarManagement.filter;


import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.CarManagement.common.Result;
import com.example.CarManagement.exception.ServiceException;
import com.example.CarManagement.sys.entity.LoginUser;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Component
public class JWTAuthenticationFilter extends OncePerRequestFilter {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        if ("/ws".equals(request.getRequestURI())){
            filterChain.doFilter(request, response);
            return;
        }
        if ("/sys/user/login".equals(request.getRequestURI())) {
            filterChain.doFilter(request, response);
            return;
        }
        if ("/file/download".equals(request.getRequestURI())) {
            filterChain.doFilter(request, response);
            return;
        }
        if ("/sys/user/wxLogin".equals(request.getRequestURI())) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = request.getHeader("Authorization");

        if (StrUtil.isEmpty(token)) {
            throw new ServiceException("令牌为空,请登录账号");
        }


        try {
            JWTSigner jwtSigner = JWTSignerUtil.hs512("yingyingying".getBytes(StandardCharsets.UTF_8));
            if (!JWTUtil.verify(token, jwtSigner)) {
                throw new ServiceException("令牌验证失败,请重新登录");
            }
        } catch (Exception e) {
            throw new ServiceException("令牌验证失败,请重新登录");
        }


        LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get(token);

        if (loginUser == null) {
            throw new ServiceException("令牌超时,请重新登录");
        }

        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(loginUser, null, null));

        filterChain.doFilter(request, response);
    }
}
